<template>
	<view>
		<view class="uni-header">
			<view class="uni-group">
				<view class="uni-title"></view>
				<view class="uni-sub-title"></view>
			</view>
			<view class="uni-group">
				<input class="uni-search" type="text" v-model="query" @confirm="search" placeholder="请输入搜索内容" />
				<button class="uni-button" type="default" size="mini" @click="search">搜索</button>
				<button class="uni-button" type="default" size="mini" @click="navigateTo('./add')">新增</button>
				<button class="uni-button" type="default" size="mini" :disabled="!selectedIndexs.length"
					@click="delTable">批量删除</button>

				<button class="uni-button" type="primary" @click="uploadExcel()" size="default">导入</button>

			</view>
		</view>
		<view class="uni-container">
			<unicloud-db ref="udb" :collection="collectionList"
				field="s_id,name,type_subject,type_drive_id,video_link,video_name,test_paper_ids,sort,status,t_sort,
				type_subject{_id,name,s_id},test_paper_ids{_id,name,s_id},type_drive_id{_id,name,s_id}"
				:where="where" page-data="replace" orderby="s_id desc" :getcount="true" :page-size="options.pageSize"
				:page-current="options.pageCurrent" v-slot:default="{data,pagination,loading,error,options}"
				:options="options" loadtime="manual" @load="onqueryload">
				<uni-table ref="table" :loading="loading" :emptyText="error.message || '没有更多数据'" border stripe
					type="selection" @selection-change="selectionChange">
					<uni-tr>
						<uni-th align="center" filter-type="search" @filter-change="filterChange($event, 's_id')"
							sortable @sort-change="sortChange($event, 's_id')">课程ID</uni-th>
						<uni-th align="center" filter-type="search" @filter-change="filterChange($event, 'name')"
							sortable @sort-change="sortChange($event, 'name')">课程昵称</uni-th>
						<uni-th align="center" sortable @sort-change="sortChange($event, 'type_subject')">科目类型</uni-th>
						<uni-th align="center" sortable @sort-change="sortChange($event, 'type_drive_id')">车型</uni-th>
			<!-- 			<uni-th align="center" sortable @sort-change="sortChange($event, 'video_link')">视频链接</uni-th>
						<uni-th align="center" sortable @sort-change="sortChange($event, 'video_name')">视频昵称</uni-th> -->
						<!-- <uni-th align="center" sortable @sort-change="sortChange($event, 'test_paper_ids')">试卷</uni-th> -->
						<uni-th align="center" filter-type="range" @filter-change="filterChange($event, 'sort')"
							sortable @sort-change="sortChange($event, 'sort')">排序</uni-th>
						<uni-th align="center" filter-type="select" :filter-data="options.filterData.status_localdata"
							@filter-change="filterChange($event, 'status')">启用状态</uni-th>
						<uni-th align="center">操作</uni-th>
					</uni-tr>
					<uni-tr v-for="(item,index) in data" :key="index">
						<uni-td align="center">{{item.s_id}}</uni-td>
						<uni-td align="center">{{item.name}}</uni-td>
						<uni-td align="center">
							<view v-for="(isb,ids) in item.type_subject" >
								{{isb.name}}({{isb.s_id}})
							</view>
							
						</uni-td>
						<uni-td align="center">
							<view v-for="(item,index) in item.type_drive_id" >
								<uni-tag :text="item.name" type="primary"></uni-tag>
							</view>
						</uni-td> 
					<!-- 	<uni-td align="center">
							<view v-for="(item,index) in item.video_link">
								<uni-tag :text="item" type="royal"></uni-tag>
							</view>
						</uni-td>
						<uni-td align="center">
							<view v-for="(item,index) in item.video_name">
								<uni-tag :text="item" type="royal"></uni-tag>
							</view>
						</uni-td> -->
					<!-- 	<uni-td align="center">
							<view v-for="(item,index) in item.test_paper_ids" >
								<uni-tag :text="item.name" type="royal"></uni-tag>
							</view>
						</uni-td> -->
						<uni-td align="center">{{item.sort}}</uni-td>
						<uni-td align="center">{{options.status_valuetotext[item.status]}}</uni-td>
						<uni-td align="center">
							<view class="uni-group">
								<button @click="navigateTo('./edit?id='+item._id, false)" class="uni-button" size="mini"
								type_drive_id	type="primary">修改</button>
								<button @click="confirmDelete(item._id)" class="uni-button" size="mini"
									type="warn">删除</button>
								<button class="uni-button" type="primary" size="mini" @click="befordownload(index)">导出
									Excel</button>
							</view>
						</uni-td>
					</uni-tr>
				</uni-table>

				<download-excel ref="excelDownload" v-show="false" class="hide-on-phone" :fields="exportExcel.fields"
					:data="exportExcelData" :type="exportExcel.type" :name="exportExcel.filename">

				</download-excel>


				<view class="uni-pagination-box">
					<uni-pagination show-icon :page-size="pagination.size" v-model="pagination.current"
						:total="pagination.count" @change="onPageChanged" />
				</view>
			</unicloud-db>
		</view>
	</view>
</template>

<script>
	import {
		enumConverter,
		filterToWhere
	} from '@/js_sdk/validator/subject-page.js';
	import * as XLSX from '@/js_sdk/xlsx/dist/xlsx.full.min.js'
	const db = uniCloud.database()
	// 表查询配置
	const dbOrderBy = 'sid asc' // 排序字段
	const dbSearchFields = [] // 模糊搜索字段，支持模糊搜索的字段列表。联表查询格式: 主表字段名.副表字段名，例如用户表关联角色表 role.role_name
	// 分页配置
	const pageSize = 20
	const pageCurrent = 1

	const orderByMapping = {
		"ascending": "asc",
		"descending": "desc"
	}

	export default {
		data() {
			return {
				cachedata: [],
				collectionList: [
					db.collection('subject-page').getTemp(),
					db.collection('type-drive').getTemp(),
					db.collection('test-paper').getTemp(),
					db.collection('type-subject').getTemp()
				],
				query: '',
				where: '',
				orderby: dbOrderBy,
				orderByFieldName: "",
				selectedIndexs: [],
				options: {
					pageSize,
					pageCurrent,
					filterData: {
						"status_localdata": [{
								"text": "正常",
								"value": 0
							},
							{
								"text": "禁用",
								"value": 1
							}
						]
					},
					...enumConverter
				},
				imageStyles: {
					width: 64,
					height: 64
				},
				exportExcel: {
					"filename": "subject-page.xls",
					"type": "xls",
					"fields": {
						"课程ID": "s_id",
						"课程昵称": "name",
						"科目类型": "type_subject",
						"车型": "type_drive_id",
						"视频链接": "video_link",
						"视频昵称": "video_name",
						"试卷": "test_paper_ids",
						"排序": "sort",
						"启用状态": "status",
						"试卷排序": "t_sort"
					}
				},
				exportExcelData: []
			}
		},
		onLoad() {
			this._filter = {}
		},
		onReady() {
			this.$refs.udb.loadData()
		},
		methods: {

			/**
			 * 
			 * 	"课程ID": "s_id",
			"课程昵称": "name",
			"科目类型": "type_subject",
			"驾驶证类型": "type_drive_id",
			"视频链接": "video_link",
			"视频昵称": "video_name",
			"试卷": "test_paper_ids",
			"排序": "sort",
			"试卷排序":"t_sort",
			"启用状态": "status"
			 */

			async befordownload(index) {
				// this.exportExcelData

				
				console.log(this.cachedata[index])
				this.exportExcelData = []
				
				let type_drive = this.cachedata[index]['type_drive_id']
				let c = type_drive.map(v=> v.s_id)
				let type_subject = this.cachedata[index]['type_subject']
				let s = type_subject.map(v=>v.s_id)
				
				let header = {
					"s_id": this.cachedata[index]['s_id'],
					"name": this.cachedata[index]['name'],
					"type_subject": s.join('|'),
					"type_drive_id":c.join('|') ,
					"video_name": this.cachedata[index]['video_name'][0],
					"video_link": this.cachedata[index]['video_link'][0],
					"test_paper_ids": this.cachedata[index]['test_paper_ids'][0].s_id,
					"t_sort": this.cachedata[index]['t_sort'][0]
				}
				this.exportExcelData.push(header)
				for (let i = 1; i < this.cachedata[index]['test_paper_ids'].length; i++) {
					this.exportExcelData.push({
						"video_link": this.cachedata[index]['video_link'][i],
						"video_name": this.cachedata[index]['video_name'][i],
						"test_paper_ids": this.cachedata[index]['test_paper_ids'][i].s_id,
						"t_sort": this.cachedata[index]['t_sort'][i]
					})
				}

				this.$nextTick(async () => {
					await this.$refs.excelDownload.generate()
				})



			},
			onqueryload(data) {
				this.cachedata = this.$cloneObject(data)

			},

			// onqueryload(data) {
			//   this.exportExcelData = data
			// },
			getWhere() {
				const query = this.query.trim()
				if (!query) {
					return ''
				}
				const queryRe = new RegExp(query, 'i')
				return dbSearchFields.map(name => queryRe + '.test(' + name + ')').join(' || ')
			},
			search() {
				const newWhere = this.getWhere()
				this.where = newWhere
				this.$nextTick(() => {
					this.loadData()
				})
			},
			loadData(clear = true) {
				this.$refs.udb.loadData({
					clear
				})
			},
			onPageChanged(e) {
				this.selectedIndexs.length = 0
				this.$refs.table.clearSelection()
				this.$refs.udb.loadData({
					current: e.current
				})
			},
			navigateTo(url, clear) {
				// clear 表示刷新列表时是否清除页码，true 表示刷新并回到列表第 1 页，默认为 true
				uni.navigateTo({
					url,
					events: {
						refreshData: () => {
							this.loadData(clear)
						}
					}
				})
			},
			// 多选处理
			selectedItems() {
				var dataList = this.$refs.udb.dataList
				return this.selectedIndexs.map(i => dataList[i]._id)
			},
			// 批量删除
			delTable() {
				this.$refs.udb.remove(this.selectedItems(), {
					success: (res) => {
						this.$refs.table.clearSelection()
					}
				})
			},
			// 多选
			selectionChange(e) {
				this.selectedIndexs = e.detail.index
			},
			confirmDelete(id) {
				this.$refs.udb.remove(id, {
					success: (res) => {
						this.$refs.table.clearSelection()
					}
				})
			},
			sortChange(e, name) {
				this.orderByFieldName = name;
				if (e.order) {
					this.orderby = name + ' ' + orderByMapping[e.order]
				} else {
					this.orderby = ''
				}
				this.$refs.table.clearSelection()
				this.$nextTick(() => {
					this.$refs.udb.loadData()
				})
			},
			filterChange(e, name) {
				this._filter[name] = {
					type: e.filterType,
					value: e.filter
				}
				let newWhere = filterToWhere(this._filter, db.command)
				if (Object.keys(newWhere).length) {
					this.where = newWhere
				} else {
					this.where = ''
				}
				this.$nextTick(() => {
					this.$refs.udb.loadData()
				})
			},

			uploadExcel() {
				const self = this
				uni.chooseFile({
					async success(res) {

						const url = res.tempFilePaths[0];
						const data = await (await fetch(url, {
							mode: 'no-cors'
						})).arrayBuffer();
						/* data is an ArrayBuffer */
						const workbook = XLSX.read(data);
						const xlsxData = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]])
						let keyMap = Object.keys(self.exportExcel.fields)

						/**
							"课程ID": "s_id",
							"课程昵称": "name",
							"科目类型": "type_subject",
							"驾驶证类型": "type_drive_id",
							"视频链接": "video_link",
							"视频昵称": "video_name",
							"试卷": "test_paper_ids",
							"排序": "sort",
							"启用状态": "status"
						 */

						let header = {
							s_id: xlsxData[0]['课程ID'].toString(),
							sid:xlsxData[0]['课程ID'],
							name: xlsxData[0]['课程昵称'].toString(),
							type_subject: xlsxData[0]['科目类型'].toString(),
							type_drive_id: xlsxData[0]['车型'].toString().split('|'),
							t_sort: [],
							video_link: [],
							video_name: [],
							test_paper_ids: [],
							status: 0
						}
						if(xlsxData[0]['视频链接']){
								header.video_link.push(xlsxData[0]['视频链接'])
						}
						if(xlsxData[0]['视频昵称']){
							header.video_name.push(xlsxData[0]['视频昵称'])
						}
						header.test_paper_ids.push(xlsxData[0]['试卷'].toString())
						header.t_sort.push(xlsxData[0]['试卷排序'])
						for (let i = 1; i < xlsxData.length; i++) {
							// if(xlsxData[0]['视频链接']){
							// 		header.video_link.push(xlsxData[i]['视频链接'])
							// }
							// if(xlsxData[0]['视频昵称']){
							// 	header.video_name.push(xlsxData[i]['视频昵称'])
							// }
							header.test_paper_ids.push(xlsxData[i]['试卷'].toString())
							header.t_sort.push(xlsxData[i]['试卷排序'])
						}
						console.log(header.test_paper_ids)
				
						const q_list = await db.collection('test-paper').where({
								s_id: db.command.in(header.test_paper_ids)
							})
							.field('s_id')
							.distinct('s_id')
							.limit(500)
							.get()
			
						let map = new Map()
						let notId = []
						for (let row of q_list.result.data) {
							map.set(row.s_id, true)
						}
						for (let row of header.test_paper_ids) {
							if (!map.has(row)) {
								notId.push(row)
							}
						}
						if (notId.length > 0) {
							uni.showModal({
								content: "试卷集合:" + notId.join(',') + "不存在",
								showCancel: false,
								confirmText: '复制错误信息',
								success(res) {
									if (res.confirm) {
										uni.setClipboardData({
											data: notId.join(','),
											success(info) {
												uni.showToast({
													title: '复制成功',
													duration: 1500,
													icon: 'none'
												})
											}
										})
									}
								}
							})
							return;
						}

						await db.collection('subject-page').add(header).then((res) => {
							uni.showToast({
								title: '新增成功'
							})
							self.$nextTick(() => {
								self.$refs.udb.refresh()
							})
						}).catch((err) => {
							console.log(err)
							uni.showModal({
								content: err.message,
								showCancel: false
							})
						})

					}
				})

			}

		}
	}
</script>

<style>
</style>
